package com.photons.artp.rpc

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.photons.artp.CameraStreamConsumer
import io.grpc.BindableService
import io.grpc.Server
import io.grpc.netty.NettyServerBuilder
import java.lang.Exception

class GRPCService : Service() {
    private val TAG = "GRPCService"
    private var mServer: Server? = null
    private var mCameraStreamConsumer: CameraStreamConsumer? = null

    inner class LocalBinder: Binder() {
        val service: GRPCService
            get() = this@GRPCService
    }

    fun getConsumer(): CameraStreamConsumer? {
        return mCameraStreamConsumer
    }

    override fun onCreate() {
        super.onCreate()

        publish(CameraRPCService())
    }

    override fun onDestroy() {
        super.onDestroy()

        shutdown()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private fun publish(service: CameraRPCService) {
        if (mServer != null) {
            return
        }

        mCameraStreamConsumer = service.getCameraStreamConsumer()
        mServer = NettyServerBuilder.forPort(8888).apply {
            addService(service)
        }.build()

        try {
            mServer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
            mServer = null
        }
    }

    private fun shutdown() {
        mCameraStreamConsumer = null

        mServer?.shutdown()
        mServer = null
    }
}